import pygame
from pygame.sprite import Sprite


class Ship(Sprite):
    """管理飞船的类"""

    def __init__(self, ai_game):
        """初始化飞船并设置其初始位置"""
        super().__init__()
        self.screen = ai_game.screen
        self.setting = ai_game.settings
        self.screen_rect = self.screen.get_rect()

        # 加载飞船图像并获取其外接矩形
        self.image = pygame.image.load('images/ship.png')
        self.rect = self.image.get_rect()

        # 对于每艘新飞船，都将其放在屏幕底部的中央
        self.rect.midbottom = self.screen_rect.midbottom
        # 移动标志
        self.moving_right = False
        self.moving_left = False
        self.moving_up = False
        self.moving_down = False

        # 飞船X坐标存储为小数
        self.x = float(self.rect.x)
        self.y = float(self.rect.y)

    def move(self):
        """根据移动标志移动飞船位置"""
        if self.moving_right is True and self.rect.centerx < self.screen_rect.right - 5:
            self.x += self.setting.ship_speed
        if self.moving_left is True and self.rect.centerx > 5:
            self.x -= self.setting.ship_speed
        if self.moving_up is True and self.rect.centery > 5:
            self.y -= self.setting.ship_speed
        if self.moving_down is True and self.rect.centery < self.screen_rect.bottom - 15:
            self.y += self.setting.ship_speed
        # 把值重新返还给图片矩形
        self.rect.x = self.x
        self.rect.y = self.y

    def blitm(self):
        """在指定位置绘制飞船"""
        self.screen.blit(self.image, self.rect)

    def center_ship(self):
        """让飞船在屏幕底部居中"""
        self.rect.midbottom = self.screen_rect.midbottom
        self.x = float(self.rect.x)
        self.y = float(self.rect.y)
